<template>
  <el-dialog
    :close-on-click-modal="false"
    :visible="updateUserOrg"
    class="zdy-dialog"
    width="1000px"
    :title="$t('Modify Organization')"
    :before-close="handleCloseDialog"
  >
    <div class="el-dialog-div">
      <!--组织树-->
      <div class="treeView">
        <!--<p>组织</p>-->
        <div class="searchView centerPersonView">
          <el-input
            size="small"
            class="searchInput"
            prefix-icon="el-icon-search"
            :placeholder="placeholderTips"
            v-model="filterTextOrg"
          >
          </el-input>
          <el-checkbox
            @change="leftPersonChange"
            :disabled="!orgInfo.length"
            v-model="leftPersonAll"
            >{{ this.i18n.t("All") }}</el-checkbox
          >
        </div>
        <el-tree
          v-loading="orgInfoTreeLoading"
          :element-loading-background="loadingBG"
          id="leftTree"
          class="filter-tree"
          show-checkbox
          node-key="id"
          :data="orgInfo"
          :props="orgInfoProps"
          :check-strictly="false"
          default-expand-all
          :check-on-click-node="true"
          @check-change="orgInfocheck"
          :filter-node-method="filterNodeOrg"
          ref="orgInfoTree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <i
              v-if="data.sex == undefined"
              class="orgIcon el-icon-office-building"
            ></i>
            <i
              v-if="data.sex !== undefined"
              :class="{ female: data.sex == 1 }"
              class="el-icon-user-solid userIcon"
              style="margin-right: 5px"
            ></i>
            <span
              :title="node.label"
              v-if="data.sex == undefined"
              class="departmentName"
              >{{ node.label }}</span
            >
            <span
              :title="node.label"
              v-if="data.sex !== undefined"
              class="treeUserName"
              >{{ node.label }}</span
            >
          </span>
        </el-tree>
        <el-button
          :loading="moveLoading"
          id="move"
          @click="moveRight"
          icon="el-icon-d-arrow-right"
          circle
        ></el-button>
      </div>
      <!--已选人员-->
      <div class="treeView person">
        <!--<p>人员</p>-->
        <div class="searchView">
          <!--已选-->
          <span style="line-height: 35px"
            >{{ this.i18n.t("selected") }} {{ selectedPersonList.length }}</span
          >
          <!--清空-->
          <i
            v-if="selectedPersonList.length"
            :title="$t('empty')"
            @click="clearAll"
            class="el-icon-delete clearBtn"
          ></i>
        </div>
        <div class="personView filter-tree">
          <ul style="">
            <li
              v-for="(item, index) in selectedPersonList"
              :key="item.id"
              class="personList"
            >
              <span class="centerName">{{ item.name }}</span>
              <!--删除-->
              <i
                :title="$t('delete')"
                @click="deleteSelectedList(item)"
                class="el-icon-error"
              ></i>
            </li>
            <p class="el-tree__empty-text" v-if="!selectedPersonList.length">
              {{ this.i18n.t("No data available") }}
            </p>
          </ul>
        </div>
      </div>
      <div class="treeView orgList">
        <div class="searchView centerPersonView">
        </div>
        <el-tree
          class="filter-tree"
          show-checkbox
          :element-loading-background="loadingBG"
          v-loading="onlinedevLoading"
          :empty-text="$t('No data available')"
          :data="orgRightTree"
          node-key="id"
          :check-on-click-node="true"
          :props="rightProps"
          default-expand-all
          :render-content="renderContent"
          :check-strictly="true"
          @check="rightPersonChange"
          ref="orgTree"
        >
        </el-tree>
      </div>
    </div>
    <br />
    <div class="footBtnBox">
      <!--取消-->
      <el-button size="small" type="handle" @click="handleCloseDialog">{{
        this.i18n.t("Cancel")
      }}</el-button>
      <!--保存-->
      <el-button size="small" type="primary" :loading="saveloading" @click="submitForm">{{
        this.i18n.t("save")
      }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { batchupdatepersondepartment } from "@/api/kqgl"
import { filterTreeData, traverseDep } from "./utils.js";
import { getdepartmenttree } from "@/api/pcmj/zzxx";
export default {
  name: "updateUserOrg",
  components: {},
  props: {
    updateUserOrg: {
      type: Boolean,
      default: false,
    },
    editTableRow: {
      type: Object,
      defautl: () => {
        return {};
      },
    },
  },
  watch: {
    filterTextOrg(val) {
      this.$refs.orgInfoTree.filter(val);
    },
    filterTextDev(val) {
      this.$refs.orgTree.filter(val);
    },
  },
  data() {
    return {
      leftPersonAll: false,
      rightPersonAll: false,
      saveloading: false,
      moveLoading: false,
      onlinedevLoading: false,
      filterTextOrg: "",
      filterTextDev: "",
      loadingBG: "rgba(255, 255, 255, 0.8)",
      orgInfoTreeLoading: false,
      orgRightTree: [],
      selectedPersonList: [],
      selectedRightList: [],
      orgInfo: [],
      placeholderTips: this.i18n.t("Please enter keywords"),
      filterText: "",
      orgInfoProps: {
        children: "children",
        label: "name",
        disabled: function (data, node) {
          if (data.sex == undefined) {
            return false;
          } else {
            return false;
          }
        },
      },
      rightProps: {
        children: "children",
        label: "name",
      },
      leftPersionIdList: [],
      selectOrg: {}
    };
  },
  methods: {
    // 递归检测父元素或自己是否符合条件
    filterNodeAndParent(param) {
      param.map((item) => {
        if (item.children) {
          this.filterNodeAndParent(item.children);
        }
        this.leftPersionIdList.push(item.id); // 保存每次遍历的结果
      });
    },
    leftPersonChange(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs.orgInfoTree.setCheckedNodes(this.orgInfo);
        });
      } else {
        this.$refs.orgInfoTree.setCheckedKeys([]);
      }
    },
    rightPersonChange(node,list) {
      this.selectOrg = node
      if (list.checkedKeys.length == 2) {
          this.$refs.orgTree.setCheckedKeys([node.id]);
      }
    },
    // 获取右侧树
    getRightTree() {
      this.orgInfoTreeLoading = true;
      this.$nextTick(async () => {
        getdepartmenttree({ IncludePersonInfo: true })
          .then((res) => {
            if (res.code === 200) {
              this.orgRightTree = filterTreeData(res)
            }
          })
          .catch()
          .finally(() => {
            setTimeout(() => {
              this.orgInfoTreeLoading = false;
            }, 500);
          });
      });
    },
    renderContent(h, { node, data, store }) {
      if(data.sex == undefined){
        return(
          <span class="custom-tree-node">
            <span title={node.label} class="treeUserName">{node.label}</span>
          </span>
        )
      }else{
        this.remove(node, data)
      }
    },
    // 删除节点数据方法
    remove(node, data) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },
    // 已选列表删除
    deleteSelectedList(row) {
      console.log(row);
      if (row.id !== null) {
        this.selectedPersonList.map((item, index, arr) => {
          if (item.id == row.id) {
            // 删除当前点击项
            arr.splice(index, 1);
            // 左侧组织树取消被点击的选中状态
            this.$refs.orgInfoTree.setChecked(row, false);
          }
        });
        this.leftPersonAll = false;
      }
    },
    // 组织树复选框取消选中时，删除右侧已选列表中的数据
    orgInfocheck(data, val) {
      if (!val) {
        this.leftPersonAll = false;
        if (this.selectedPersonList.length) {
          this.selectedPersonList.map((item, index, arr) => {
            if (item.id == data.id) {
              this.selectedPersonList.splice(index, 1);
            }
          });
        }
      }
      var selectedPersionList = this.$refs.orgInfoTree.getCheckedNodes();
    },
    // 清空全部已选择的人员
    clearAll() {
      // 确定要清空已选列表吗
      this.W.$myConfirm(
        "warning",
        this.i18n.t("Are you sure you want to clear the selected list")
      )
        .then(async () => {
          this.leftPersonAll = false;
          this.selectedPersonList = [];
          this.$refs.orgInfoTree.setCheckedKeys([]);
        })
        .catch(() => {});
    },
    // 移动按钮
    moveRight() {
      this.moveLoading = true;
      var checkedKeys = this.getOrginfoCheckedKeys();
      if (checkedKeys.length) {
        var result = [];
        checkedKeys.map((item) => {
          if (item.sex !== undefined) {
            result.push(item);
          }
        });
        this.selectedPersonList = result;
        console.log("移动的数据", this.selectedPersonList);
      } else {
        // 请在左侧选择要移动的人员!
        this.W.$tips(
          "warning",
          this.i18n.t("Please select the person to move on the left")
        );
      }
      setTimeout(() => {
        this.moveLoading = false;
      }, 200);
    },
    // 获取组织树下选中的人员
    getOrginfoCheckedKeys() {
      return this.$refs.orgInfoTree.getCheckedNodes();
    },
    getCheckedNodes() {
      console.log(this.getOrginfoCheckedKeys());
    },
    getCheckedKeys() {
      console.log(this.$refs.orgInfoTree.getCheckedKeys());
    },
    /**
     * @description  获取部门人员树
     * @param :
     **/
    getdepartmenttree() {
      this.orgInfoTreeLoading = true;
      this.$nextTick(async () => {
        getdepartmenttree({ IncludePersonInfo: true })
          .then((res) => {
            if (res.code === 200) {
              this.orgInfo = filterTreeData(res);
            }
          })
          .catch()
          .finally(() => {
            setTimeout(() => {
              this.orgInfoTreeLoading = false;
            }, 500);
          });
      });
    },
    filterNodeOrg(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleCloseDialog() {
      this.$emit("update:updateUserOrg", false);
      this.$emit("update:editTableRow", null);
    },
    submitForm() {
      if (!this.selectedPersonList.length) {
        // 请在左侧选择人员
        this.W.$tips(
          "warning",
          this.i18n.t("Please select personnel on the left side")
        );
        return;
      }
      if(Object.keys(this.selectOrg).length==0) {
          this.W.$tips('warning', this.i18n.t('Please select the organization to modify'));
          return
      }
      this.saveloading = true;
      this.selectedPersonList.forEach(item => {
        item.departmentInfoId = this.selectOrg.id
      })
      batchupdatepersondepartment(this.selectedPersonList).then(res => {
            this.W.$tips("success", this.i18n.t('Modified successfully!'));
            this.handleCloseDialog()
            this.$emit("getdepartmenttree");
            this.$emit("onSearch");
        }).catch(() => {

        })
    },
  },
  mounted() {
    // 获取组织树
    this.getdepartmenttree();
    // 获取右侧树
    this.getRightTree();
  },
};
</script>

<style lang="scss" scoped>
.el-dialog-div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 550px;
  overflow-x: hidden;

  .searchView {
    background: #e6eaf5;
    padding: 10px 15px;
    height: 52px;
    position: relative;
    box-sizing: border-box;
    :deep(.searchInput.el-input .el-input__inner) {
      border-radius: 50px;
      font-size: 14px;
    }
    :deep(.el-input__inner::placeholder) {
      font-size: 14px;
    }
    .searchInput {
      .el-input__inner {
        font-size: 11px;
      }
    }
    i:hover {
      cursor: pointer;
    }
    &.centerPersonView {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .searchInput {
        margin-right: 10px;
      }
    }
  }
  .importSelect {
  }

  .filter-tree {
    background: #f0f2f7;
    height: calc(100% - 90px);
  }
  .personView.filter-tree {
    overflow-y: scroll;
    position: relative;
    .personList {
      padding: 5px 15px;
      position: relative;
      border: 1px solid transparent;
      border-bottom: 1px solid #e5e8ef;
      box-sizing: border-box;
      i {
        color: #babfcf;
        float: right;
        cursor: pointer;
        margin-top: 3px;
      }
      &:hover {
        /*background:#9aa9bf;*/
        border: 1px solid #babfcf;
      }
      .centerName {
        border: 0px solid red;
        display: inline-block;
        /*vertical-align: bottom;*/
        width: 180px;
      }
    }
  }
  .treeView {
    width: 280px;
    height: 100%;
    margin: 0 10px;
    position: relative;
    /*display: inline-block;*/
    /*border: 1px solid green;*/
    /*padding: 0 !important;*/
    box-sizing: border-box;
    &.person {
      margin-left: 100px;
    }
    #move {
      position: absolute;
      right: -75px;
      top: 45%;
    }
    .departmentName,
    .treeUserName {
      /*width: 150px;*/
      border: 0px solid red;
      display: inline-block;
      vertical-align: middle;
    }
    .treeUserName {
      width: 155px;
    }
    .departmentName {
      width: 170px;
    }
    .departmentName,
    .treeUserName,
    .personList .centerName{
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
#leftTree {
  /*border: 1px solid red;*/
  height: calc(100% - 90px);
  overflow-y: scroll !important;
  .userIcon,
  .orgIcon {
    color: #0084ff;
    &.female {
      color: #ff7700;
    }
  }
  .orgIcon {
    margin-right: 5px;
  }
  .treeTool {
    .treeToolIcon {
      color: #409eff;
      /*font-weight: bold;*/
      margin-left: 8px;
      vertical-align: middle;
    }
  }
}
.clearBtn {
  float: right;
  margin-top: 10px;
  margin-right: 5px;
}
::v-deep .orgList .el-tree-node .custom-tree-node{
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: inline-block;
  white-space: nowrap;
}
</style>
